package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminUserMapper;
import com.heima.admin.service.AdminLoginService;
import com.heima.model.admin.dtos.AdminUserDto;
import com.heima.model.admin.pojos.AdminUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;

/**
 * @author ybw
 * @version 1.0
 * @date 2021/12/22 9:23
 */
@Service
@Slf4j
@Transactional
public class AdminLoginServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser>
    implements AdminLoginService {

  @Autowired private AdminUserMapper adminUserMapper;

  /**
   * 用户登录
   *
   * @param adminUserDto
   * @return
   */
  @Override
  public ResponseResult login(AdminUserDto adminUserDto) {
    // 参数校验
    if (ObjectUtils.isEmpty(adminUserDto)) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    // 获取传参
    String postName = adminUserDto.getName();
    String postPassword = adminUserDto.getPassword();
    if (StringUtils.isEmpty(postName) || StringUtils.isEmpty(postPassword)) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
    }
    // 根据用户名查询数据库
    LambdaQueryWrapper<AdminUser> qw = new LambdaQueryWrapper<>();
    qw.eq(AdminUser::getName, postName);
    AdminUser adminUser = adminUserMapper.selectOne(qw);
    if (ObjectUtils.isEmpty(adminUser)) {
      // 查不出来，没有此用户
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
    // 有此用户，获取盐和密码
    String salt = adminUser.getSalt();
    String password = adminUser.getPassword();
    // 将前台传来的密码手动加盐
    String str = postPassword + salt;
    String md5Password = DigestUtils.md5DigestAsHex(str.getBytes());
    // 判断
    if (!md5Password.equals(password)) {
      // 密码错误
      return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }
    // 登录成功，修改登录时间
    adminUser.setLoginTime(new Date());
    adminUserMapper.updateById(adminUser);
    // 封装返回值对象
    HashMap<String, Object> retMap = new HashMap<>();
    adminUser.setPassword("");
    adminUser.setSalt("");
    retMap.put("user", adminUser);
    // 生成token
    String token = AppJwtUtil.getToken(adminUser.getId().longValue());
    retMap.put("token", token);
    return ResponseResult.okResult(retMap);
  }
}
